package com.icinfo.cloud.provider.punish.ucase.punishinform.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.config.dto.CompareDiscretionDto;
import com.icinfo.cloud.provider.punish.config.dto.CompareSingleDiscretionDto;
import com.icinfo.cloud.provider.punish.config.enums.DecideBasisTypeEnum;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.IConfigOrgDecideBasisInfoService;
import com.icinfo.cloud.provider.punish.config.service.IConfigOrgRegulatoryDiscretionRuleHisService;
import com.icinfo.cloud.provider.punish.config.vo.DiscretionHisVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandleTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PunishKindsEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainDetailAuxiliaryInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesRecordVo;
import com.icinfo.cloud.provider.punish.ucase.punishinform.dto.InformHtmlRequest;
import com.icinfo.cloud.provider.punish.ucase.punishinform.dto.PunishInformFormDto;
import com.icinfo.cloud.provider.punish.ucase.punishinform.service.IPunishInformService;
import com.icinfo.cloud.provider.punish.ucase.punishinform.vo.PunishInfo;
import com.icinfo.cloud.provider.punish.ucase.punishinform.vo.PunishInformFormVo;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PunishInformServiceImpl extends MyBatisServiceSupport implements IPunishInformService {
    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CaseMainDetailAuxiliaryInfoMapper caseMainDetailAuxiliaryInfoMapper;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private IConfigOrgDecideBasisInfoService configOrgDecideBasisInfoService;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private ICaseMainDetailAuxiliaryInfoService caseMainDetailAuxiliaryInfoService;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;

    @Resource
    private IConfigOrgRegulatoryDiscretionRuleHisService configOrgRegulatoryDiscretionRuleHisService;

    /**
     * 获取处罚告知表单数据
     *
     * @param request
     * @return {@link PunishInformFormVo}
     * @author liyafeng
     * @date 2022/2/26
     */
    @Override
    public PunishInformFormVo getPunishInformFormBaseinfo(InformHtmlRequest request) {
        PunishInformFormVo punishInformFormVo = new PunishInformFormVo();
        CaseMainInfo mainInfo = caseMainInfoMapper.selectByPrimaryKey(request.getCaseId());
        punishInformFormVo.setCaseId(mainInfo.getId());
        punishInformFormVo.setCaseTerritoryCode(mainInfo.getCaseTerritoryCode());
        punishInformFormVo.setCasePartiesReasonType(mainInfo.getCasePartiesReasonType());
        punishInformFormVo.setHandleType(mainInfo.getHandleType());
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(request.getCaseId());
        punishInformFormVo.setIsNeedCollectiveDiscuss(caseMainDetailInfo.getIsNeedCollectiveDiscuss());
        punishInformFormVo.setInvestConclusion(caseMainDetailInfo.getInvestConclusion());
        punishInformFormVo.setConfiscateIllegalPropertyValue(caseMainDetailInfo.getConfiscateIllegalPropertyValue());
        // 非分别处罚
        if (!StringUtils.equals(HandleTypeEnum.PART_PUNISH.getCode(), mainInfo.getHandleType())) {
            punishInformFormVo.setPunishType(caseMainDetailInfo.getPunishKinds());
            punishInformFormVo.setPunishMoney(caseMainDetailInfo.getDraftPunishMoney());
            punishInformFormVo.setConfiscateIllegalMoney(caseMainDetailInfo.getConfiscateIllegalMoney());
            punishInformFormVo.setConfiscateIllegalProperty(caseMainDetailInfo.getConfiscateIllegalProperty());
            //不是符合听证时,查询机构听证判定依据配置获取是否符合听证条件,如果从通过移动端调取则每次都从配置判断是否听证
            if (!YesOrNoEnum.YES.getCode().equals(caseMainDetailInfo.getIsHearing())
                    || Boolean.TRUE.equals(request.getIsMobile())) {
                String isHearing = dealIsHearing(mainInfo, caseMainDetailInfo, null);
                punishInformFormVo.setIsHearing(isHearing);
            } else {
                punishInformFormVo.setIsHearing(caseMainDetailInfo.getIsHearing());
            }
            //获取告知处理内容
            Example example = new Example(CaseMainDetailAuxiliaryInfo.class);
            example.createCriteria().andEqualTo("caseId", request.getCaseId());
            List<CaseMainDetailAuxiliaryInfo> auxiliaryInfoList = caseMainDetailAuxiliaryInfoMapper.selectByExample(example);
            if(CollectionUtil.isNotEmpty(auxiliaryInfoList)){
                punishInformFormVo.setDisposeContext(auxiliaryInfoList.get(0).getDisposeContext());
            }
            punishInformFormVo.setDiscretionHisVo(configOrgRegulatoryDiscretionRuleHisService.getDiscretionHisByRuleHisId(caseMainDetailInfo.getIllegalSituation()));
        }
        // 多案由
        if (StringUtils.equals(PartiesReasonTypeEnum.MULTIPLE_REASONS.getCode(), mainInfo.getCasePartiesReasonType())) {
            Example example = new Example(CaseMainDetailAuxiliaryInfo.class);
            example.createCriteria().andEqualTo("caseId", request.getCaseId());
            List<CaseMainDetailAuxiliaryInfo> auxiliaryInfoList = caseMainDetailAuxiliaryInfoMapper.selectByExample(example);
            punishInformFormVo.setPunishInfoList(getPunishInfoVoList(auxiliaryInfoList));
        }
        // 多当事人分别处罚
        if (StringUtils.equals(PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode(), mainInfo.getCasePartiesReasonType())
                && StringUtils.equals(HandleTypeEnum.PART_PUNISH.getCode(), mainInfo.getHandleType()) && StringUtils.isNotBlank(request.getPartyId())) {
            Example example = new Example(CaseMainDetailAuxiliaryInfo.class);
            example.createCriteria().andEqualTo("caseId", request.getCaseId()).andEqualTo("partyId", request.getPartyId());
            List<CaseMainDetailAuxiliaryInfo> auxiliaryInfoList = caseMainDetailAuxiliaryInfoMapper.selectByExample(example);
            dealIsHearing(mainInfo, null, auxiliaryInfoList);
            punishInformFormVo.setPunishInfoList(getPunishInfoVoList(auxiliaryInfoList));
        }
        return punishInformFormVo;
    }

    /**
     * 获取处罚信息列表
     */
    private List<PunishInfo> getPunishInfoVoList(List<CaseMainDetailAuxiliaryInfo> auxiliaryInfoList) {
        // 得到违法情形的ruleHisId
        List<String> ruleHisIds = auxiliaryInfoList.stream()
                .map(CaseMainDetailAuxiliaryInfo::getIllegalSituation)
                .filter(StrUtil::isNotBlank).distinct().collect(Collectors.toList());
        // 得到具体的自由裁量信息 key(ruleHisId) -> value(DiscretionHisVo)
        Map<String, DiscretionHisVo> discretionHisByRuleHisIds = configOrgRegulatoryDiscretionRuleHisService.getDiscretionHisByRuleHisIds(ruleHisIds);
        return auxiliaryInfoList.stream()
                .map(a -> convertPunishInfoVo(a, discretionHisByRuleHisIds.get(a.getIllegalSituation())))
                .collect(Collectors.toList());
    }

    /**
     * 转换当事人处罚信息
     */
    private PunishInfo convertPunishInfoVo(CaseMainDetailAuxiliaryInfo info, DiscretionHisVo discretionHisVo){
        PunishInfo punishInfo = new PunishInfo();
        BeanUtils.copyProperties(info, punishInfo);
        punishInfo.setDiscretionHisVo(discretionHisVo);
        return punishInfo;
    }

    /**
     * 是否符合听证条件逻辑处理
     *
     * @param mainInfo
     * @param caseMainDetailInfo
     * @param auxiliaryInfoList
     * @return
     */
    private String dealIsHearing(CaseMainInfo mainInfo, CaseMainDetailInfo caseMainDetailInfo, List<CaseMainDetailAuxiliaryInfo> auxiliaryInfoList) {
        String isNeedHearing = YesOrNoEnum.NO.getCode();
        //案件id
        String caseId = mainInfo.getId();
        //判定依据类型:集体议案
        String decideBasisType = DecideBasisTypeEnum.HEARING.getCode();

        if (StringUtils.equals(PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode(), mainInfo.getCasePartiesReasonType())
                && StringUtils.equals(HandleTypeEnum.PART_PUNISH.getCode(), mainInfo.getHandleType())) {
            if (ObjectUtils.isEmpty(auxiliaryInfoList)) {
                return isNeedHearing;
            }

            for (CaseMainDetailAuxiliaryInfo auxiliaryInfo : auxiliaryInfoList) {
                //处罚金额
                String draftPunishMoney = auxiliaryInfo.getDraftPunishMoney();
                //没收违法所得
                String confiscateIllegalMoney = auxiliaryInfo.getConfiscateIllegalMoney();
                //没收非法财务
                String confiscateIllegalPropertyValue = auxiliaryInfo.getConfiscateIllegalPropertyValue();
                //当前案件处罚种类
                List<String> punishKindsList = Arrays.asList(auxiliaryInfo.getPunishKinds().split(","));
                //查询当事人信息
                Example example=new Example(CasePartiesRecord.class);
                example.createCriteria().andEqualTo("partyId", auxiliaryInfo.getPartyId()).andEqualTo("status", Constant.STRING_1);
                List<CasePartiesRecord> casePartiesRecords = casePartiesRecordMapper.selectByExample(example);
                if (ObjectUtils.isEmpty(casePartiesRecords)) {
                    break;
                }

                String partyType = casePartiesRecords.get(0).getPartyType();
                String result = configOrgDecideBasisInfoService.checkIsNeedByConfigOrgDecideBasis(caseId, decideBasisType, punishKindsList, draftPunishMoney, confiscateIllegalMoney, partyType, confiscateIllegalPropertyValue);
                if (YesOrNoEnum.NO.getCode().equals(result)) {
                    break;
                }

                isNeedHearing = YesOrNoEnum.YES.getCode();
                auxiliaryInfo.setIsHearing(isNeedHearing);
            }

        } else {
            //处罚金额
            String draftPunishMoney = caseMainDetailInfo.getDraftPunishMoney();
            //没收违法所得
            String confiscateIllegalMoney = caseMainDetailInfo.getConfiscateIllegalMoney();
            //没收非法财务
            String confiscateIllegalPropertyValue = caseMainDetailInfo.getConfiscateIllegalPropertyValue();
            //查询当事人信息
            List<CasePartiesRecordVo> casePartiesRecords = casePartiesRecordService.getCasePartiesInfo(caseId);
            String partyType = casePartiesRecords.get(0).getPartyType();
            if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(mainInfo.getCasePartiesReasonType())) {
                //多当事人合并处罚,当事人包含单位则按单位额度
                boolean b = casePartiesRecords.stream().anyMatch(casePartiesRecordVo -> PartyTypeEnum.LEGAL.getCode().equals(casePartiesRecordVo.getPartyType()));
                if (b) {
                    partyType = PartyTypeEnum.LEGAL.getCode();
                }
            }
            //当前案件处罚种类
            List<String> punishKindsList = Arrays.asList(caseMainDetailInfo.getPunishKinds().split(","));
            isNeedHearing = configOrgDecideBasisInfoService.checkIsNeedByConfigOrgDecideBasis(caseId, decideBasisType, punishKindsList, draftPunishMoney, confiscateIllegalMoney, partyType, confiscateIllegalPropertyValue);
        }
        return isNeedHearing;
    }

    /**
     * 保存处罚告知表单数据
     *
     * @param
     * @return {@link int}
     * @author liyafeng
     * @date 2022/2/26
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int savePunishInformForm(PunishInformFormDto punishInformFormDto) {
        // 校验多当事人、多案由、或者单当事人单案由的违法情形数据
        checkAmount(punishInformFormDto);
        //是否听证发成变化时, 处罚告知相关文书处理
        log.info("savePunishInformForm params => {}", JSON.toJSONString(punishInformFormDto));
        if (DocumentKindEnum.DOC_KIND_CFGZSPB.getCode().equals(punishInformFormDto.getDocumentKindCode())) {
            dealPunishInformDocument(punishInformFormDto);
        }

        // 非分别处罚
        if (!StringUtils.equals(HandleTypeEnum.PART_PUNISH.getCode(), punishInformFormDto.getHandleType())) {
            CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
            updateCaseMainDetailInfo.setCaseId(punishInformFormDto.getCaseId());
            updateCaseMainDetailInfo.setConfiscateIllegalMoney(punishInformFormDto.getConfiscateIllegalMoney());
            updateCaseMainDetailInfo.setIsHearing(punishInformFormDto.getIsHearing());
            updateCaseMainDetailInfo.setPunishKinds(punishInformFormDto.getPunishType());
            updateCaseMainDetailInfo.setDraftPunishMoney(punishInformFormDto.getPunishMoney());
            updateCaseMainDetailInfo.setConfiscateIllegalProperty(punishInformFormDto.getConfiscateIllegalProperty());
            updateCaseMainDetailInfo.setConfiscateIllegalPropertyValue(punishInformFormDto.getConfiscateIllegalPropertyValue());
            updateCaseMainDetailInfo.setInvestConclusion(punishInformFormDto.getInvestConclusion());
            caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);
            try {
                //单当事人单案由 更新补充表数据
                CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
                caseMainDetailAuxiliaryInfo.setCaseId(punishInformFormDto.getCaseId());
                caseMainDetailAuxiliaryInfo.setConfiscateIllegalMoney(punishInformFormDto.getConfiscateIllegalMoney());
                caseMainDetailAuxiliaryInfo.setIsHearing(punishInformFormDto.getIsHearing());
                caseMainDetailAuxiliaryInfo.setPunishKinds(punishInformFormDto.getPunishType());
                caseMainDetailAuxiliaryInfo.setDraftPunishMoney(punishInformFormDto.getPunishMoney());
                caseMainDetailAuxiliaryInfo.setConfiscateIllegalProperty(punishInformFormDto.getConfiscateIllegalProperty());
                caseMainDetailAuxiliaryInfo.setDisposeContext(punishInformFormDto.getDisposeContext());
                caseMainDetailAuxiliaryInfo.setConfiscateIllegalPropertyValue(punishInformFormDto.getConfiscateIllegalPropertyValue());
                caseMainDetailAuxiliaryInfoService.editSpecialParamSingle(caseMainDetailAuxiliaryInfo);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        // 更新案件详情补充表
        if (CollectionUtils.isNotEmpty(punishInformFormDto.getPunishInfoList())) {
            List<CaseMainDetailAuxiliaryInfo> auxiliaryInfoList = JSONObject.parseArray(JSONObject.toJSONString(punishInformFormDto.getPunishInfoList()), CaseMainDetailAuxiliaryInfo.class);
            for (CaseMainDetailAuxiliaryInfo auxiliaryInfo : auxiliaryInfoList) {
                caseMainDetailAuxiliaryInfoMapper.updateByPrimaryKeySelective(auxiliaryInfo);
            }
        }
        return 1;
    }
    /**
     * 检查处罚金额是否满足裁量信息
     */
    private void checkAmount(PunishInformFormDto dto) {
        // 不予处罚不校验
        if (Constant.STRING_2.equals(dto.getInvestConclusion())) {
            return;
        }
        // 1：单案由单当事人 2：多案由单当事人 3：单案由多当事人
        String casePartiesReasonType = dto.getCasePartiesReasonType();
        // 1：合并处罚 2：分别处罚
        String handleType = dto.getHandleType();

        // 单当事人单案由
        if (Constant.STRING_1.equals(casePartiesReasonType) && dto.getPunishType().contains(PunishKindsEnum.PunishKind_2.getDes())) {
            structureSingletonCompareForPunishInform(dto);
        }
        // 多案由单当事人
        if (Constant.STRING_2.equals(casePartiesReasonType)) {
            structureCompareForPunishInform(dto);
        }
        // 单案由多当事人 合并处罚  罚款
        if (Constant.STRING_3.equals(casePartiesReasonType)
                && Constant.STRING_1.equals(handleType)
                && dto.getPunishType().contains(PunishKindsEnum.PunishKind_2.getDes())) {
            structureSingletonCompareForPunishInform(dto);
        }
        // 单案由多当事人 分别处罚
        if (Constant.STRING_3.equals(casePartiesReasonType) && Constant.STRING_2.equals(handleType)){
            structureCompareForPunishInform(dto);
        }

    }

    /**
     * 多案由单当事人 或 单案由多当事人分别处罚 的裁量参数组装
     */
    private void structureCompareForPunishInform(PunishInformFormDto dto) {
        // 裁量校验参数初始化
        CompareDiscretionDto compareParam = new CompareDiscretionDto();
        List<PunishInfo> punishInfoList = dto.getPunishInfoList();
        List<String> discretionIds = punishInfoList.stream()
                .filter(r -> r.getPunishKinds().contains(PunishKindsEnum.PunishKind_2.getDes()) && Objects.nonNull(r.getDiscretionHisVo()))
                .map(p -> p.getDiscretionHisVo().getRuleHisId()).collect(Collectors.toList());
        Map<String, String> punishInfoMap = punishInfoList.stream()
                .filter(r -> r.getPunishKinds().contains(PunishKindsEnum.PunishKind_2.getDes()) && Objects.nonNull(r.getDiscretionHisVo()))
                .collect(Collectors.toMap(p -> p.getDiscretionHisVo().getRuleHisId(), PunishInfo::getDraftPunishMoney));
        compareParam.setDiscretionRuleHisIds(discretionIds);
        compareParam.setPunishInfoMap(punishInfoMap);
        configOrgRegulatoryDiscretionRuleHisService.verifyDiscretionAmount(compareParam);
    }

    /**
     * 单当事人单案由 或 单案由多当事人合并处罚 的裁量参数组装
     */
    private void structureSingletonCompareForPunishInform(PunishInformFormDto dto) {
        DiscretionHisVo discretionHisVo = dto.getDiscretionHisVo();
        if (Objects.isNull(discretionHisVo)){
            return;
        }
        CompareSingleDiscretionDto param = new CompareSingleDiscretionDto(discretionHisVo.getRuleHisId(), dto.getPunishMoney());
        configOrgRegulatoryDiscretionRuleHisService.verifySingleDiscretionAmount(param);
    }

    /**
     * 是否听证切换处罚告知相关文书处理
     *
     * @param punishInformFormDto
     */
    private void dealPunishInformDocument(PunishInformFormDto punishInformFormDto) {
        boolean isChange = false;
        String caseId = punishInformFormDto.getCaseId();
        String partyId = null;
        //非分别处罚
        if (!StringUtils.equals(HandleTypeEnum.PART_PUNISH.getCode(), punishInformFormDto.getHandleType())) {
            CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(caseId);
            //判断是否听证有无改变
            if (!ObjectUtils.isEmpty(caseMainDetailInfo.getIsHearing())
                    && !Objects.equals(punishInformFormDto.getIsHearing(), caseMainDetailInfo.getIsHearing())) {
                log.info("dealPunishInformDocument willChange");
                isChange = true;
            }
        } else {
            log.info("dealPunishInformDocument else logic");
            if (ObjectUtils.isEmpty(punishInformFormDto.getPunishInfoList())) {
                return;
            }
            List<CaseMainDetailAuxiliaryInfo> auxiliaryInfoList = JSONObject.parseArray(JSONObject.toJSONString(punishInformFormDto.getPunishInfoList()), CaseMainDetailAuxiliaryInfo.class);
            CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = auxiliaryInfoList.get(0);
            partyId = caseMainDetailAuxiliaryInfo.getPartyId();
            //查询原来是否存在补充记录
            Example auxiliaryExample = new Example(CaseMainDetailAuxiliaryInfo.class);
            auxiliaryExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("partyId", caseMainDetailAuxiliaryInfo.getPartyId());
            List<CaseMainDetailAuxiliaryInfo> oldCaseMainDetailAuxiliaryInfos = caseMainDetailAuxiliaryInfoMapper.selectByExample(auxiliaryExample);
            if (ObjectUtils.isEmpty(oldCaseMainDetailAuxiliaryInfos)) {
                return;
            }
            CaseMainDetailAuxiliaryInfo oldCaseMainDetailAuxiliaryInfo = oldCaseMainDetailAuxiliaryInfos.get(0);
            //判断是否听证有无改变
            if (!ObjectUtils.isEmpty(oldCaseMainDetailAuxiliaryInfo.getIsHearing())
                    && !oldCaseMainDetailAuxiliaryInfo.getIsHearing().equals(caseMainDetailAuxiliaryInfo.getIsHearing())) {
                isChange = true;
            }
        }

        if (isChange) {
            CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
            //是否听证isHearing发生变化时删除之前保存的文书--不处理的话会生成两种告知书
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo =
                    configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_CFGZSPB.getCode());
            String relationDocumentCatalogCode = configBusiParamDocumentInfo.getRelationDocumentCatalogCode();
            log.info("DOC_KIND_CFGZSPB config => {}", JSON.toJSONString(configBusiParamDocumentInfo));
            if (!ObjectUtils.isEmpty(relationDocumentCatalogCode)) {
                relationDocumentCatalogCode = configBusiParamDocumentInfo.getDocumentCatalogCode() + "," + relationDocumentCatalogCode;
                String[] catalogCodeArr = relationDocumentCatalogCode.split(",");
                log.info("will delete catalogCode => {}", JSON.toJSONString(catalogCodeArr));
                for (String catalogCode : catalogCodeArr) {
                    //删除文书记录
                    //查询文书记录数据
                    Example relateExample = new Example(CaseDocumentRecord.class);
                    Example.Criteria criteria = relateExample.createCriteria();
                    criteria.andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", catalogCode)
                            .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
                    if (!ObjectUtils.isEmpty(partyId)) {
                        criteria.andEqualTo("partyId", partyId);
                    }
                    int rows = caseDocumentRecordMapper.deleteByExample(relateExample);
                    log.info("delete catalogCode [{}] rows => {}", catalogCode, rows);
                }
            }
        }

    }

    /**
     * 描述： 查询是否符合听证条件
     *
     * @author: zhengqiang
     * @date: 2022/7/11
     * @param: punishInformFormDto
     * @return {@link Result < String>}
     **/
    @Override
    public Result<String> getIsNeedHearingResult(PunishInformFormDto formDto) {
        String isNeedHearing = YesOrNoEnum.NO.getCode();
        //案件id
        String caseId = formDto.getCaseId();
        //判定依据类型:集体议案
        String decideBasisType = DecideBasisTypeEnum.HEARING.getCode();

        String casePartiesReasonType = formDto.getCasePartiesReasonType();
        String handleType = formDto.getHandleType();
        //多当事人分别处罚
        if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)
                && HandleTypeEnum.PART_PUNISH.getCode().equals(handleType)) {
            List<PunishInfo> punishInfoList = formDto.getPunishInfoList();
            if (ObjectUtils.isEmpty(punishInfoList)) {
                return Result.success("success", YesOrNoEnum.NO.getCode());
            }

            for (PunishInfo punishInfo : punishInfoList) {
                //处罚金额
                String draftPunishMoney = punishInfo.getDraftPunishMoney();
                //没收违法所得
                String confiscateIllegalMoney = punishInfo.getConfiscateIllegalMoney();
                //没收非法财务
                String confiscateIllegalPropertyValue = punishInfo.getConfiscateIllegalPropertyValue();
                //处罚种类为空
                if (ObjectUtils.isEmpty(punishInfo.getPunishKinds())) {
                    return Result.success("success", YesOrNoEnum.NO.getCode());
                }
                //当前案件处罚种类
                List<String> punishKindsList = Arrays.asList(punishInfo.getPunishKinds().split(","));
                //查询当事人信息
                Example example=new Example(CasePartiesRecord.class);
                example.createCriteria().andEqualTo("partyId", punishInfo.getPartyId()).andEqualTo("status", Constant.STRING_1);
                List<CasePartiesRecord> casePartiesRecords = casePartiesRecordMapper.selectByExample(example);
                if (ObjectUtils.isEmpty(casePartiesRecords)) {
                    return Result.success("success", YesOrNoEnum.NO.getCode());
                }

                String partyType = casePartiesRecords.get(0).getPartyType();
                String result = configOrgDecideBasisInfoService.checkIsNeedByConfigOrgDecideBasis(caseId, decideBasisType, punishKindsList, draftPunishMoney, confiscateIllegalMoney, partyType, confiscateIllegalPropertyValue);
                if (YesOrNoEnum.NO.getCode().equals(result)) {
                    return Result.success("success", YesOrNoEnum.NO.getCode());
                }

                isNeedHearing = YesOrNoEnum.YES.getCode();
            }

        } else {
            //处罚种类为空
            if (ObjectUtils.isEmpty(formDto.getPunishType())) {
                return Result.success("success", YesOrNoEnum.NO.getCode());
            }
            //处罚金额
            String draftPunishMoney = formDto.getPunishMoney();
            //没收违法所得
            String confiscateIllegalMoney = formDto.getConfiscateIllegalMoney();
            //没收非法财务
            String confiscateIllegalPropertyValue = formDto.getConfiscateIllegalPropertyValue();
            //查询当事人信息
            List<CasePartiesRecordVo> casePartiesRecords = casePartiesRecordService.getCasePartiesInfo(formDto.getCaseId());
            String partyType = casePartiesRecords.get(0).getPartyType();
            if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)) {
                //默认为个人
                partyType = PartyTypeEnum.PERSON.getCode();
                //多当事人合并处罚,当事人包含单位则按单位额度
                boolean b = casePartiesRecords.stream().anyMatch(casePartiesRecordVo -> PartyTypeEnum.LEGAL.getCode().equals(casePartiesRecordVo.getPartyType()));
                if (b) {
                    partyType = PartyTypeEnum.LEGAL.getCode();
                }
            }
            //当前案件处罚种类
            List<String> punishKindsList = Arrays.asList(formDto.getPunishType().split(","));

            isNeedHearing = configOrgDecideBasisInfoService.checkIsNeedByConfigOrgDecideBasis(caseId, decideBasisType, punishKindsList, draftPunishMoney, confiscateIllegalMoney, partyType, confiscateIllegalPropertyValue);
        }
        return Result.success("success", isNeedHearing);
    }

}
